#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/10 21:41
# @Author  : lizhen
# @Site    : 
# @File    : cNumpy.py
# @Software: PyCharm
import numpy as np
from numpy.matlib import randn


class NumpyDemo:
    def __init__(self):
        self.arr = np.array([1, 2, 3], dtype=np.float64)

    def _test_create(self):
        """
        nd = NumpyDemo()
        nd._test_create()
        """
        arr = self.arr
        print(arr, arr.dtype, arr.ndim, arr.shape)
        print(np.zeros((3, 6)))
        print(np.empty((2, 3, 2)))
        print(np.arange(15))
        print(arr.astype(np.int32))
        print(np.float64(arr))
        print(np.string_(arr))
        print(np.unicode_(arr))

    def _test_calculate(self):
        """
        nd = NumpyDemo()
        nd._test_calculate()
        """
        arr = self.arr
        print(arr * arr)
        print(arr - arr)
        print(1 / arr)

    def _test_shape(self):
        """
        nd = NumpyDemo()
        nd._test_shape()
        """
        self.arr = np.arange(32).reshape((8, 4))
        arr = self.arr
        print(arr)
        print(arr[1:3, :])  # 正常切片
        print(arr[[1, 2, 3]])  # 花式索引
        print(arr.T)
        print(arr.transpose())
        print(arr.swapaxes(1, 0))  # 转置
        print(arr.dot(arr.transpose()))  # 矩阵内积
        print(np.sqrt(arr))
        print(np.exp(arr))

    def _test_advance(self):
        """
        nd = NumpyDemo()
        nd._test_advance()
        """
        print(randn(8))  # 正态分布值
        print(np.maximum([1, 2, 3], [1, 1, 6]))
        print(np.where(1 > 2, [1, 2, 3], [1, 1, 6]))  # 当cond为真，取xarr, 否则取yarr
        self.arr = np.arange(32).reshape((8, 4))
        arr = self.arr
        print(arr.mean())
        print(arr.mean(axis=1))  # 算术平均数
        print(arr.sum())
        print(arr.std())
        print(arr.var())  # 和、标准差、方差
        print(arr.min())
        print(arr.max())  # 最小值、最大值
        print(arr.argmin())
        print(arr.argmax())  # 最小索引、最大索引
        print(arr.cumsum())
        print(arr.cumprod())  # 所有元素的累计和、累计积
        print(arr.all())
        print(arr.any())  # 检查数组中是否全为真、部分为真
        arr.sort()
        print(arr)
        arr.sort(1)  # 排序、1轴向上排序
        print(arr)
        print(np.unique(arr))  # 去重
        print(np.in1d(arr, [0, 1, 23]))  # arr1的值是否在arr2中
        np.save('ext/cNumpy/numpyDemo', arr)
        np.savez('ext/cNumpy/numpyDemo', {0: arr, 1: arr})  # 读取、保存文件
        np.savetxt('ext/cNumpy/numpyDemo.txt', arr, delimiter=',', newline='\n')
        print(np.load('ext/cNumpy/numpyDemo.npy'))
        print(np.loadtxt('ext/cNumpy/numpyDemo.txt', delimiter=','))
        arr1 = np.arange(8).reshape(4, 2)
        print(np.concatenate([arr1, arr1], axis=0))  # 连接两个arr，按行的方向


if __name__ == '__main__':
    nd = NumpyDemo()
    nd._test_advance()
